package com.example.springcloudgateway.gatewayconfig;

import com.example.springcloudgateway.gatewayconfig.filters.TestFilter;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 路由配置，可在数据库动态配置，但是修改了数据库之后需要重启项目
 * 开放actuator接口后，访问 http://localhost:8001/actuator/gateway/routes 查勘所有路由信息
 */
@Configuration
public class GatewayConfiguration {
    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {
        RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
        routes.route(
                "ribbon-service",   //路由id
                r -> doPredicate(r).filters(this::doFilter) //根据路径进行断言匹配
                        .uri("http://localhost:9090/")) // 断言成功后进行跳转
                .build();

//        routes.route("ribbon-service1",
//                r -> r.before(ZonedDateTime.parse("2021-05-14 16:37:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.of("CTT", ZoneId.SHORT_IDS)))) //根据时间断言
//                        .uri("http://localhost:9090/")).build();
        return routes.build();
    }

    private UriSpec doFilter(GatewayFilterSpec gatewayFilterSpec) {
        return gatewayFilterSpec.addRequestHeader("xxx", "aaaa").filter(new TestFilter());
    }

    private BooleanSpec doPredicate(PredicateSpec predicateSpec) {
        return predicateSpec.path("/**");
    }
}
